package com.yupi.springbootinit.bizmq;

import com.rabbitmq.client.Channel;
import com.yupi.springbootinit.common.ErrorCode;
import com.yupi.springbootinit.constant.BiMqConstant;
import com.yupi.springbootinit.constant.CommonConstant;
import com.yupi.springbootinit.exception.BusinessException;
import com.yupi.springbootinit.manager.AiManager;
import com.yupi.springbootinit.model.entity.Chart;
import com.yupi.springbootinit.service.ChartService;
import com.yupi.springbootinit.utils.EasyExcelUtils;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * ClassName: MyMessageConsumer
 * Package: com.yupi.springbootinit.bizmq
 * Description:
 *
 * @Author:
 * @Create: 2024/4/4 - 20:55
 * @Version: v1.0
 */
@Component
@Slf4j
public class BiMessageConsumer {

    @Resource
    private ChartService chartService;

    @Resource
    private AiManager aiManager;

    //指定程序监听的消息队列和确认机制
    @SneakyThrows(value = Exception.class)
    @RabbitListener(queues = {BiMqConstant.BI_QUEUE_NAME}, ackMode = "MANUAL")
    public void receiveMessage(String message, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) {
        if (StringUtils.isBlank(message)) {
            //任务失败，拒绝消息
            channel.basicNack(deliveryTag, false, false);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "消息为空");
        }
        long chartId = Long.parseLong(message);
        //通过图表id获取chart
        Chart chart = chartService.getById(chartId);
        if (chart == null) {
            channel.basicNack(deliveryTag, false, false);
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "图表信息为空");
        }

        // 先修改图表的任务状态为 “执行中 running”，任务执行完毕后修改状态为 succeed，执行失败也要修改 failed
        Chart updateChart = new Chart();
        updateChart.setId(chart.getId());
        updateChart.setChartStatus("running");
        boolean updateResult = chartService.updateById(updateChart);
        if (!updateResult) {
            //修改图表状态失败，也要将 图表状态修改为 failed
            channel.basicNack(deliveryTag, false, false);
            chartService.handleChartUpdateError(chart.getId(), "状态改为 running失败");
            return;
        }

        //调用AI
        String chartString = aiManager.doChat(CommonConstant.BI_MODEL_ID, buildUserInput(chart));
        //将得到的 chartString处理
        String[] splits = chartString.split("【【【【【");
        if (splits.length > 3) {
            channel.basicNack(deliveryTag, false, false);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "AI 生成错误");
        }
        String genChart = splits[1].trim();
        String genResult = splits[2].trim();
        Chart resultChart = new Chart();
        resultChart.setId(chart.getId());
        resultChart.setGenChart(genChart);
        resultChart.setGenResult(genResult);
        resultChart.setChartStatus("succeed");
        boolean result = chartService.updateById(resultChart);
        if (!result) {
            channel.basicNack(deliveryTag, false, false);
            chartService.handleChartUpdateError(chartId, "状态改为 succeed失败");
            return;
        }
        //任务成功，就 确认消息
        channel.basicAck(deliveryTag, false);
    }


    /**
     * 构建用户输入
     * @param chart
     * @return
     */
    private String buildUserInput(Chart chart) {
        String goal = chart.getGoal();
        String chartType = chart.getChartType();
        String chartData = chart.getChartData();
        //用户输入
        StringBuilder userInput = new StringBuilder();
        String userGoal = goal;
        if (StringUtils.isNotBlank(chartType)) {
            userGoal += ",请使用" + chartType;
        }
        userInput.append("分析需求:").append("\n");
        userInput.append(userGoal).append("\n");

        userInput.append("原始数据:").append("\n");
        userInput.append(chartData).append("\n");
        return userInput.toString();
    }
}
